package com.donleo.stmg.aop;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.donleo.stmg.common.api.CommonResult;
import com.donleo.stmg.entity.mapper.TeamMapper;
import com.donleo.stmg.entity.model.Team;
import com.donleo.stmg.entity.model.User;
import com.donleo.stmg.relation.mapper.UserTeamRelationMapper;
import com.donleo.stmg.relation.model.UserTeamRelation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author liangd
 * @since 2021/1/5 10:26
 */
@Component
@Aspect
public class TeamAspect {

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private UserTeamRelationMapper userTeamRelationMapper;

    /**
     * 配置切点方法
     */
    @Pointcut("execution(public * com.donleo.stmg.entity.service.impl.TeamServiceImpl.distributeMembers(..))")
    public void pointCut() {
    }

    /**
     * 判断小组成员是否为空，为空则设置组长为空
     *
     * @param joinPoint
     * @param result
     */
    @AfterReturning(value = "pointCut()", returning = "result")
    public void deleteTeamLeader(JoinPoint joinPoint, Object result) {
        Object[] args = joinPoint.getArgs();
        String teamCode = (String) args[0];
        CommonResult commonResult = (CommonResult) result;
        long code = commonResult.getCode();
        List<UserTeamRelation> list = new LambdaQueryChainWrapper<>(userTeamRelationMapper)
                .eq(UserTeamRelation::getTeamCode, teamCode)
                .list();
        if (code == 200) {
            if (list.size() == 1) {
                UserTeamRelation userTeamRelation = list.get(0);
                if ("[]".equals(userTeamRelation.getUserCode())) {
                    teamMapper.updateTeamLeaderByCode(teamCode);
                }
            } else if (list.size() == 0) {
                teamMapper.updateTeamLeaderByCode(teamCode);
            }
        }
    }

}
